package ym.ecrm.core.dao.systemManagement.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import ym.ecrm.core.common.util.Pager;
import ym.ecrm.core.dao.base.impl.HibernateEntityDAO;
import ym.ecrm.core.dao.systemManagement.IOrganizationDAO;
import ym.ecrm.core.domain.systemManagement.Organization;

@Repository
@SuppressWarnings("unchecked")
public class HibernateOrganizationDAO extends HibernateEntityDAO<Organization> 
	implements IOrganizationDAO{

	//@Override
	public List<Organization> findOrganizationByParentId(final long parentId) {
		final String hql = "from Organization o where o.parent.id = :parentId";
		List<Organization> list = getHibernateTemplate()
				.executeFind(new HibernateCallback<List<Organization>>() {

			//@Override
			public List<Organization> doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				query.setParameter("parentId", parentId);
				return query.list();
			}
		});
		return list;
	}

	//@Override
	public Organization findRootOrganization() {
		return load(1l);
	}

	//@Override
	public Pager<Organization> findOrganizations(int pageNumber, int pageSize) {
		final String countHql = "select count(*) from Organization";
		final String hql = "from Organization";
		
		long totalCount = getHibernateTemplate().execute(
				new HibernateCallback<Long>() {

			//@Override
			public Long doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query query = session.createQuery(countHql);
				List<Long> list = query.list();
				if(list != null  && list.size() != 0){
					return list.get(0);
				}
				return 0l;
			}
		});
		
		if(totalCount <= 0){
			return null;
		}
		
		List<Organization> list = getHibernateTemplate().executeFind(
				new HibernateCallback<List<Organization>>() {

					//@Override
					public List<Organization> doInHibernate(Session session)
							throws HibernateException, SQLException {
						return session.createQuery(hql).list();
					}
		});
		
		return new Pager<Organization>(pageNumber, pageSize, totalCount, list);
	}
	
}
